package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @Author Stringzhua
 * @Date 2024/11/5 11:37
 * description:
 */
public class Demo04 {
    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取 Class 类型的对象
        Class clazz = Methodservice.class;

        // 获取方法
        Method m1 = clazz.getMethod("buy");
        Method m2 = clazz.getMethod("sth", int.class, double.class);
        Method m3 = clazz.getMethod("sth", String.class);
        Method m4 = clazz.getMethod("todo");

        // 执行实例方法
        Object obj = clazz.newInstance();

        // 类似:m.buy()
        m1.invoke(obj);

        Object returnm2 = m2.invoke(obj, 3, 3.14);
        System.out.println(returnm2);

        Object returnm3 = m3.invoke(obj, "测试");
        System.out.println(returnm3);

        m4.invoke(null);

    }
}

class Methodservice {
    public void buy() {
        System.out.println("buy()...");
    }

    public int sth(int a, double b) {
        System.out.println("sth(int a,double b)...");
        int sum = a + (int) b;
        System.out.println("和为" + sum);
        return sum;
    }

    public String sth(String s) {
        System.out.println("sth(String s)");
        return UUID.randomUUID().toString();
    }

    public static void todo() {
        System.out.println("todo()...");
    }
}